package com.leyou.user.service;

import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.config.JwtProperties;
import com.leyou.user.entity.*;
import com.leyou.user.mapper.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProvinceMapper provinceMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private UserMessageMapper userMessageMapper;


    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    public Boolean checkUsernameOrPhone(String data, Integer type) {
        User entity = new User();
        switch (type) {
            case 1:
                entity.setUsername(data);
                break;
            case 2:
                entity.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        QueryWrapper<User> wrapper = Wrappers.query(entity);
        //根据条件查询数量
        Integer count = userMapper.selectCount(wrapper);
        return count != 1;
    }

    public void sendCode(String phone) {
        //生成6位数字验证码
        String code = RandomStringUtils.randomNumeric(6);
        //将验证码放入redis中
        redisTemplate.opsForValue().set(LyConstants.CODE_KEY_PRE+phone, code, 2, TimeUnit.DAYS);
        //封装mq发送消息的对象
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);
        //将验证码发给用户
        amqpTemplate.convertAndSend(MQConstants.Exchange.SMS_EXCHANGE_NAME,
                MQConstants.RoutingKey.VERIFY_CODE_KEY, map);
    }

    public void register(User user, String code) {
        //从redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(LyConstants.CODE_KEY_PRE + user.getPhone());
        //比对验证码
        if(!StringUtils.equals(redisCode, code)){
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //入库
        int count = userMapper.insert(user);
        if(count!=1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public User findUsernameAndPassword(String username, String password) {
        //根据用户名查询用户对象
        User entity = new User();
        entity.setUsername(username);
        QueryWrapper<User> wrapper = Wrappers.query(entity);
        User user = userMapper.selectOne(wrapper);
        //判空
        if(user==null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //比对密码是否正确
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        if(!matches){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return user;
    }

    //查找所有省份
    public List<Province> findAllProvicne() {
        QueryWrapper<Province> query = Wrappers.query();
        List<Province> provinces = provinceMapper.selectList(query);
        return provinces;
    }

    public List<City> findCitiesByProvinceId(String provinceId) {
        Map<String, String> map = new HashMap<>();
        City entity = new City();
        entity.setProvinceid(provinceId);
        QueryWrapper<City> query = Wrappers.query(entity);
        List<City> cities = cityMapper.selectList(query);
        return cities;
    }

    public List<Area> findAreaByCityId(String cityId) {
        Map<String, String> map = new HashMap<>();
        Area entity = new Area();
        entity.setCityid(cityId);
        QueryWrapper<Area> query = Wrappers.query(entity);
        List<Area> areas = areaMapper.selectList(query);
        return areas;
    }


    @Autowired
    private JwtProperties jwtProp;

    /**
     * 保存用户数据
     * @param userMessage
     * @param request
     */
    public void saveUserMessage(UserMessage userMessage , HttpServletRequest request) {
        if (userMessage.getId() != null){
            //修改
            userMessageMapper.updateById(userMessage);
        }else{
            //获取用户id
            String token = CookieUtils.getCookieValue(request, jwtProp.getCookie().getCookieName());
            //解析校验token
            if(StringUtils.isEmpty(token)){
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            Payload<UserInfo> payload = null;
            try {
                payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
            }catch (Exception e){
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            //返回用户信息
            UserInfo userInfo = payload.getUserInfo();
            Long userid = userInfo.getId();
            userMessage.setId(userid);
            userMessageMapper.insert(userMessage);
        }

    }

    /**
     * 查询用户数据
     * @param request
     * @return
     */
    public UserMessage findUserMessage(HttpServletRequest request) {
        //获取用户id
        String token = CookieUtils.getCookieValue(request, jwtProp.getCookie().getCookieName());
        //解析校验token
        if(StringUtils.isEmpty(token)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //返回用户信息
        UserInfo userInfo = payload.getUserInfo();
        Long userid = userInfo.getId();
        UserMessage userMessage = userMessageMapper.selectById(userid);
        if (userMessage == null){
            throw new LyException(ExceptionEnum.INVALID_NOTIFY_PARAM);
        }
        return userMessage;

    }


}
